package com.yao.myioc.factory.support;

import com.yao.myioc.definition.BeanDefinition;
import com.yao.myioc.factory.ListableBeanFactory;
import com.yao.myioc.registry.BeanDefinitionRegistry;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * beanFactory中集大成的一个类
 *
 * @author Henry Yao
 */
public class DefaultListableBeanFactory extends AbstractAutowiredCapableBeanFactory implements BeanDefinitionRegistry, ListableBeanFactory {
    private final Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();

    @Override
    public void addBeanDefinition(String name, BeanDefinition bd) {
        beanDefinitionMap.put(name, bd);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) {
        return beanDefinitionMap.get(beanName);
    }

    @Override
    public List<BeanDefinition> getBeanDefinitions() {
        return new ArrayList<>(beanDefinitionMap.values());
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> List<T> getBeansByType(Class<T> type) {
        List<T> list = new ArrayList<>();
        for (BeanDefinition bd : beanDefinitionMap.values()) {
            try {
                Class<?> clazz = Class.forName(bd.getClazzName());
                // 判断类是不是bean的父类
                if (type.isAssignableFrom(clazz)) {
                    list.add((T) getBean(bd.getBeanName()));
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    @Override
    public List<String> getBeanNamesByType(Class<?> type) {
        List<String> list = new ArrayList<>();
        for (BeanDefinition bd : beanDefinitionMap.values()) {
            try {
                Class<?> clazz = Class.forName(bd.getClazzName());
                if (type.isAssignableFrom(clazz)) {
                    list.add(bd.getBeanName());
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
